<?php
namespace core;
use core\lib\Log;
use \core\lib\Route;
class Core {
    protected $assign = array();

    static public function run() {

       Log::init(); // 初始化加载日志系统
       $Route = new Route();
       $controller = ucfirst(Route::$controller);
       $action = Route::$action;
       $ctrl_file = ROOT . MODULE . '/controller/' . $controller . 'Controller.php';
       // echo $ctrl_file;
       if(is_file($ctrl_file)) {
            include $ctrl_file;
            $obj = "\app\controller\\" . $controller . 'Controller';
            $controllerObj =  new $obj();
            $controllerObj->$action();
            Log::log(array('action' => $action, 'controller' => $controller . 'Controller'));
       }else{
           throw new \Exception('找不到该控制器' . $controller . 'Controller');
       }
    }

    /*自动加载类库*/
    static public function load($class) {

        $class = str_replace('\\', '/', $class);
        $file = ROOT . '/' . $class . '.php';

        if (is_file($file)) {
            include $file;
        }else{
            return false;
        };

    }

    public function  assign($name, $value)
    {
        $this->assign[$name] = $value;
    }

    public function display($name)
    {
        // 不使用模板引擎
        $viewPath = ROOT . MODULE . '/views/' . Route::$controller . '/' . $name;
        extract($this->assign);
        if(is_file($viewPath)){
            include $viewPath;
        }else{
            throw new \Exception('找不到该视图文件' . $name);
        }

        // 使用了twig模板引擎
        /*$veiwPath = ROOT . MODULE . '/views/' . Route::$controller;
        $veiwFile = ROOT . MODULE . '/views/' . Route::$controller . '/' . $name;
        if(is_file($veiwFile)){
            $loader = new \Twig_Loader_Filesystem($veiwPath);
            $twig = new \Twig_Environment($loader, array(
                 'cache' => ROOT . '/cache/twig',
                'debug' => true
            ));
            echo $twig->render($name, $this->assign?:array());
        }else{
            throw new \Exception('找不到该视图文件' . $name);
        }*/
    }
}